package com.cserver.pro.realm;


import com.cserver.pro.entity.SysUser;
import com.cserver.pro.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class UserShiroRealm extends AuthorizingRealm {

    @Override
    public void setName(String name) {
        super.setName("userShiroRealm");
    }

    @Autowired
    private SysUserService sysUserService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SysUser sysUser =(SysUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        if("admin".equals(sysUser.getLoginName())){
            simpleAuthorizationInfo.addRole("admin");
            simpleAuthorizationInfo.addStringPermission("*:*:*");
            return simpleAuthorizationInfo;
        }else{
            simpleAuthorizationInfo.addRole("user");
            simpleAuthorizationInfo.addStringPermission("sys:user:get");
            simpleAuthorizationInfo.addStringPermission("sys:user:more");
            return simpleAuthorizationInfo;
        }
    }

    /**
     * 认证
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = "";
        if (upToken.getPassword() != null)
        {
            password = new String(upToken.getPassword());
        }

        SysUser user = sysUserService.getSysUser(username,password);
        if(user!=null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, this.getName());
            return info;
        }else{
            return null;
        }
    }
}
